package com.wwj.study.template;


import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by lenovo on 2018/11/18.
 */
public class JdbcTemplate  {

    private DataSource dataSource;
    public JdbcTemplate(DataSource dataSource){
        this.dataSource=dataSource;
    }

    public List<?> executeQuery(String sql, RowMapper<?> rowMapper, Object [] values){
        try {

            //1、获取连接
            Connection conn = this.getConnection();
            //2、创建语句集
            PreparedStatement pstmt = this.createPreparedStatement(conn,sql);
            //3、执行语句集，并且获得结果集
            ResultSet rs = this.executeQuery(pstmt,values);
            //4、解析语句集
            List<?> result = this.parseResultSet(rs,rowMapper);

            //5、关闭结果集
            this.closeResultSet(rs);
            //6、关闭语句集
            this.closeStatement(pstmt);
            //7、关闭连接
            this.closeConnection(conn);

            return result;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    private void closeConnection(Connection conn) {
        //关闭连接
    }

    private void closeStatement(PreparedStatement pstmt) throws SQLException {
        pstmt.close();
    }


    private void closeResultSet(ResultSet rs) throws SQLException {
        rs.close();
    }


    private List<?> parseResultSet(ResultSet rs, RowMapper<?> rowMapper) throws SQLException {

        List<Object> result = new ArrayList<Object>();
        int rowNum = 1;
        while (rs.next()){
            //rowMapper接口 执行实现接口的方法
            result.add(rowMapper.mapRow(rs,rowNum ++));
        }
        return result;

    }

    private ResultSet executeQuery(PreparedStatement pstmt, Object[] values) throws SQLException {
        for (int i = 0; i < values.length; i++) {
            pstmt.setObject(i, values[i]);
        }
        ResultSet r = pstmt.executeQuery();
        return r;
    }

    private PreparedStatement createPreparedStatement(Connection conn, String sql) throws SQLException {
        PreparedStatement p=conn.prepareStatement(sql);
        return p;
    }

    private Connection getConnection() throws SQLException {
        return dataSource.getConnection();
    }

}
